<template>
    <div class="question-management">
        <h4>常见问题</h4>

        <!-- 筛选区域 -->
        <el-card class="filter-card">
            <div class="filter-container">
                <div class="filter-item">
                    <span class="filter-label">问题标题：</span>
                    <el-input v-model="filterForm.problemTitle" style="width: 200px" placeholder="输入问题标题" clearable />

                    <span class="filter-label">问题分类：</span>
                    <el-select v-model="filterForm.problemType" placeholder="请选择..." clearable style="width: 150px"
                        :loading="categoriesLoading">
                        <el-option v-for="category in categories" :key="category.value" :label="category.name"
                            :value="category.value" />
                    </el-select>
                </div>
                <br>
                <el-button type="primary" @click="handleFilterImmediate" :loading="loading">筛选</el-button>
            </div>
        </el-card>

        <!-- 问题列表 -->
        <el-card class="list-card">
            <div class="list-header">
                <h5>问题列表</h5>
                <div class="list-actions">
                    <el-button type="success" @click="handleAdd" :disabled="loading">新增问题</el-button>
                    <el-tag v-if="loading" type="info" size="small">
                        <el-icon class="is-loading">
                            <Loading />
                        </el-icon>
                        加载中...
                    </el-tag>
                    <el-tag v-else-if="tableData.length > 0" type="success" size="small">
                        已加载 {{ tableData.length }} 条数据
                    </el-tag>
                </div>
            </div>

            <el-table ref="tableRef" :data="tableData" border style="width: 100%"
                @selection-change="handleSelectionChange" v-loading="loading" empty-text="暂无常见问题数据"
                :row-key="(row: any) => row.id" :default-sort="{ prop: 'addTime', order: 'descending' }">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="problemTitle" label="标题" width="300" />
                <el-table-column prop="problemType" label="分类" width="120">
                    <template #default="scope">
                        {{ getCategoryName(scope.row.problemType) }}
                    </template>
                </el-table-column>
                <el-table-column prop="createdBy" label="上传人" width="100">
                    <template #default="scope">
                        {{ scope.row.createdBy || 'admin' }}
                    </template>
                </el-table-column>
                <el-table-column prop="isrecommended" label="是否推荐" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.isrecommended ? 'success' : 'info'">
                            {{ scope.row.isrecommended ? '推荐' : '不推荐' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="addTime" label="添加时间">
                    <template #default="scope">
                        {{ moment(scope.row.addTime).format('YYYY-MM-DD HH:mm:ss') }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="260">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
                        <el-button type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <div class="pagination-left">
                    <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
                    <el-button type="danger" size="small" @click="handleBatchDelete"
                        :disabled="selectedRows.length === 0">批量删除</el-button>
                    <span class="pagination-info">共{{ page.pageCount }}页/{{ page.totalCount }}条数据</span>
                </div>
                <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="page.totalCount"
                    layout="total, sizes, prev, pager, next, jumper" prev-text="上一页" next-text="下一页"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增问题' : '编辑问题'" width="800px"
            @close="resetForm">
            <el-button type="primary" @click="dialogVisible = false"
                style="float: right; margin-bottom: 20px;">返回</el-button>

            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="right">
                <el-form-item label="问题标题" prop="problemTitle">
                    <el-input v-model="formData.problemTitle" placeholder="请输入..." />
                </el-form-item>

                <el-form-item label="分类" prop="problemType">
                    <el-select v-model="formData.problemType" placeholder="请选择分类" style="width: 200px;"
                        :loading="categoriesLoading">
                        <el-option v-for="category in categories" :key="category.value" :label="category.name"
                            :value="category.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="是否推荐" prop="isrecommended">
                    <el-switch v-model="formData.isrecommended" active-text="推荐" inactive-text="不推荐"
                        :active-value="true" :inactive-value="false" />
                </el-form-item>

                <el-form-item label="详情" prop="problemContent">
                    <div class="rich-text-editor">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" mode="default" />
                        <Editor style="height: 400px; overflow-y: hidden;" v-model="formData.problemContent"
                            :defaultConfig="editorConfig" mode="default" @onCreated="handleCreated" />
                    </div>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="resetForm">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        {{ dialogType === 'add' ? '提交' : '更新' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialogVisible" :title="currentQuestion.problemTitle" width="800px">
            <div class="question-detail">
                <div class="detail-meta">
                    <span class="meta-item">{{ moment(currentQuestion.addTime).format('YYYY.MM.DD') }}</span>
                    <el-tag :type="currentQuestion.isrecommended ? 'success' : 'info'" size="small">
                        {{ currentQuestion.isrecommended ? '推荐' : '不推荐' }}
                    </el-tag>
                </div>

                <div class="detail-question">
                    <p><strong>问：{{ currentQuestion.problemTitle }}</strong></p>
                </div>

                <div class="detail-content">
                    <div v-if="currentQuestion.problemContent" v-html="currentQuestion.problemContent"
                        class="rich-content">
                    </div>
                    <div v-else class="default-content">
                        <p>暂无详细内容</p>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch, onBeforeUnmount, shallowRef, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { readB, writeB } from '@/api/http'
import moment from 'moment'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { createEditor, createToolbar } from '@wangeditor/editor'
// @ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 响应式数据
const tableData = ref<any[]>([])
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const tableRef = ref()
const selectedRows = ref<any[]>([])
const selectAll = ref(false)
const currentQuestion = ref<any>({})
const categories = ref<any[]>([])
const categoriesLoading = ref(false)

// 富文本编辑器相关
const editorRef = shallowRef()

// 工具栏配置
const toolbarConfig = {
    excludeKeys: ['group-video', 'insertVideo', 'uploadVideo', 'codeBlock', 'group-indent']
}

// 编辑器配置
const editorConfig = {
    placeholder: '请输入问题详细回答...',
    MENU_CONF: {
        uploadImage: {
            server: 'http://localhost:5023/api/Carousel/UploadCarouselImage/upload-image?bucketName=image&prefix=question',
            fieldName: 'imageFile',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
            },
            onSuccess(file: any, res: any) {
                console.log('富文本图片上传成功', file, res)
            },
            onFailed(file: any, res: any) {
                console.log('富文本图片上传失败', file, res)
                ElMessage.error('图片上传失败')
            }
        }
    }
}

// 筛选表单
const filterForm = reactive({
    problemTitle: '',
    problemType: ''
})

// 分页参数
const page = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    pageCount: 0
})

// 表单数据
const formData = reactive({
    id: '',
    problemTitle: '',
    problemType: 0,
    isrecommended: true,
    problemContent: ''
})

// 表单验证规则
const formRules: FormRules = {
    problemTitle: [
        { required: true, message: '请输入问题标题', trigger: 'blur' }
    ],
    problemType: [
        { required: true, message: '请选择分类', trigger: 'change' }
    ],
    problemContent: [
        { required: true, message: '请输入详细回答', trigger: 'blur' }
    ]
}

// 注释掉模拟数据，现在使用真实API
// const mockData = []

// 根据分类ID获取分类名称
const getCategoryName = (categoryId: number) => {
    const category = categories.value.find(cat => cat.value === categoryId)
    return category ? category.name : '未知分类'
}

// 获取分类列表
const getCategories = async () => {
    categoriesLoading.value = true
    try {
        const response = await readB.get('/api/Questions/GetFAQCategories/categories')
        if (response.data.code == 200) {
            categories.value = response.data.data;
        } else {
            console.warn('分类数据格式不正确:', response.data)
            // 如果API返回的数据格式不正确，使用默认分类
            categories.value = [
                { name: '账号相关', value: 1 },
                { name: '支付相关', value: 2 },
                { name: '订单相关', value: 3 },
                { name: '系统使用', value: 4 },
                { name: '技术问题', value: 5 },
                { name: '其他问题', value: 6 }
            ]
        }
    } catch (error) {
        console.error('获取分类列表失败:', error)
        ElMessage.error('获取分类失败')
        // 如果API调用失败，使用默认分类
        categories.value = [
            { name: '账号相关', value: 1 },
            { name: '支付相关', value: 2 },
            { name: '订单相关', value: 3 },
            { name: '系统使用', value: 4 },
            { name: '技术问题', value: 5 },
            { name: '其他问题', value: 6 }
        ]
    } finally {
        categoriesLoading.value = false
    }
}

// 获取问题列表
const getQuestionList = async () => {
    loading.value = true
    try {
        // 准备查询参数
        const params = {
            PageIndex: page.PageIndex,
            PageSize: page.PageSize,
            ProblemTitle: filterForm.problemTitle || undefined,
            ProblemType: filterForm.problemType ? Number(filterForm.problemType) : undefined
        }

        // 调用API获取问题列表
        const response = await readB.get('/api/Questions/GetProblemList/list', { params })

        if (response.data.code === 200) {
            // 根据API返回的数据结构处理
            const data = response.data.data
            if (data && Array.isArray(data)) {
                // 如果返回的是数组，直接使用
                tableData.value = data
                page.totalCount = data.length
            } else if (data && data.list && Array.isArray(data.list)) {
                // 如果返回的是包含list的对象
                tableData.value = data.list
                page.totalCount = data.totalCount || data.list.length
            } else {
                // 其他情况
                tableData.value = []
                page.totalCount = 0
            }
            page.pageCount = Math.ceil(page.totalCount / page.PageSize)

            selectedRows.value = []
            selectAll.value = false
            if (tableRef.value) {
                tableRef.value.clearSelection()
            }
        } else {
            ElMessage.error(response.data.message || '获取数据失败')
            tableData.value = []
            page.totalCount = 0
            page.pageCount = 0
        }
    } catch (error) {
        console.error('获取常见问题列表失败:', error)
        ElMessage.error('获取数据失败')
        tableData.value = []
        page.totalCount = 0
        page.pageCount = 0
    } finally {
        loading.value = false
    }
}

// 筛选处理
const handleFilterImmediate = () => {
    page.PageIndex = 1
    getQuestionList()
}

// 新增
const handleAdd = () => {
    dialogType.value = 'add'
    resetForm()
    dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
    dialogType.value = 'edit'
    // 映射数据格式
    Object.assign(formData, {
        id: row.id,
        problemTitle: row.problemTitle,
        problemType: Number(row.problemType),
        isrecommended: row.isrecommended,
        problemContent: row.problemContent
    })
    dialogVisible.value = true
}

// 查看详情
const handleViewDetail = (row: any) => {
    currentQuestion.value = { ...row }
    detailDialogVisible.value = true
}

// 删除
const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm('确定要删除这个常见问题吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // 调用批量删除API，传入单个ID
        const response = await writeB.post('/api/Questions/BatchDeleteProblems/batch-delete', {
            ids: [row.id]
        })
        if (response.data.code === 200) {
            ElMessage.success('删除成功')
            getQuestionList()
        } else {
            ElMessage.error(response.data.message || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败，请重试')
        }
    }
}

// 批量删除
const handleBatchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的数据')
        return
    }

    try {
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条记录吗？`, '批量删除', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // 批量删除API调用
        const ids = selectedRows.value.map(row => row.id)
        const response = await writeB.post('/api/Questions/BatchDeleteProblems/batch-delete', { ids })

        if (response.data.code === 200) {
            ElMessage.success('批量删除成功')
            getQuestionList()
        } else {
            ElMessage.error(response.data.message || '批量删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败，请重试')
        }
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitLoading.value = true

        // 准备提交数据
        const submitData = {
            problemTitle: formData.problemTitle,
            problemType: formData.problemType,
            isrecommended: formData.isrecommended,
            problemContent: formData.problemContent
        }

        if (dialogType.value === 'add') {
            // 新增问题
            const response = await writeB.post('/api/Questions/AddProblem/add', submitData)
            if (response.data.code === 200) {
                ElMessage.success('新增成功')
                dialogVisible.value = false
                getQuestionList()
            } else {
                ElMessage.error(response.data.message || '新增失败')
            }
        } else {
            // 编辑问题
            const response = await writeB.put('/api/Questions/UpdateProblem/update', {
                id: formData.id,
                ...submitData
            })
            if (response.data.code === 200) {
                ElMessage.success('编辑成功')
                dialogVisible.value = false
                getQuestionList()
            } else {
                ElMessage.error(response.data.message || '编辑失败')
            }
        }
    } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败，请重试')
    } finally {
        submitLoading.value = false
    }
}

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    Object.assign(formData, {
        id: '',
        problemTitle: '',
        problemType: 0,
        isrecommended: true,
        problemContent: ''
    })
}

// 选择处理
const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
    selectAll.value = selection.length === tableData.value.length && tableData.value.length > 0
}

const handleSelectAll = (value: boolean) => {
    if (tableRef.value) {
        if (value) {
            tableRef.value.clearSelection()
            tableData.value.forEach(row => {
                tableRef.value.toggleRowSelection(row, true)
            })
        } else {
            tableRef.value.clearSelection()
        }
    }
}

// 分页处理
const handleSizeChange = (size: number) => {
    page.PageSize = size
    page.PageIndex = 1
    getQuestionList()
}

const handleCurrentChange = (current: number) => {
    page.PageIndex = current
    getQuestionList()
}

// 富文本编辑器创建后的回调
const handleCreated = (editor: any) => {
    editorRef.value = editor
}

// 组件销毁前清理编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

// 监听筛选条件变化，自动筛选
watch(() => [filterForm.problemTitle, filterForm.problemType], (newVal, oldVal) => {
    if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
        setTimeout(() => {
            handleFilterImmediate()
        }, 300)
    }
})

// 初始化
onMounted(async () => {
    await getCategories()
    getQuestionList()
})
</script>

<style scoped>
.question-management {
    padding: 20px;
}

.question-management h4 {
    margin: 0 0 20px 0;
    font-size: 20px;
    color: #333;
}

/* 筛选区域样式 */
.filter-card {
    margin-bottom: 20px;
}

.filter-container {
    padding: 10px 0;
}

.filter-item {
    display: flex;
    align-items: center;
    gap: 15px;
    flex-wrap: wrap;
}

.filter-label {
    font-size: 14px;
    color: #606266;
    white-space: nowrap;
}

/* 列表区域样式 */
.list-card {
    margin-bottom: 20px;
}

.list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.list-header h5 {
    margin: 0;
    font-size: 16px;
    color: #333;
}

.list-actions {
    display: flex;
    align-items: center;
    gap: 10px;
}

/* 分页区域样式 */
.pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #f0f0f0;
}

.pagination-left {
    display: flex;
    align-items: center;
    gap: 15px;
}

.pagination-info {
    color: #909399;
    font-size: 14px;
}

/* 富文本编辑器样式 */
.rich-text-editor {
    border: 1px solid #ccc;
    border-radius: 4px;
    overflow: hidden;
}

.rich-text-editor:focus-within {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 对话框样式 */
.dialog-footer {
    text-align: right;
}

/* 详情页样式 */
.question-detail {
    padding: 20px;
}

.detail-meta {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 20px;
    font-size: 14px;
    color: #999;
}

.meta-item {
    font-size: 14px;
    color: #999;
}

.detail-question {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;
}

.detail-question p {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.detail-content {
    line-height: 1.6;
    color: #666;
}

/* 富文本内容样式 */
.rich-content {
    line-height: 1.6;
    color: #666;
}

.rich-content p {
    margin-bottom: 15px;
    margin-top: 0;
}

.rich-content h1,
.rich-content h2,
.rich-content h3,
.rich-content h4,
.rich-content h5,
.rich-content h6 {
    margin-top: 20px;
    margin-bottom: 10px;
    color: #333;
}

.rich-content ul,
.rich-content ol {
    margin-bottom: 15px;
    padding-left: 20px;
}

.rich-content img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 10px 0;
}

.rich-content blockquote {
    margin: 15px 0;
    padding: 10px 15px;
    background-color: #f8f9fa;
    border-left: 4px solid #409eff;
    color: #666;
}

.rich-content code {
    background-color: #f1f2f3;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: monospace;
    color: #e74c3c;
}

.rich-content pre {
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 4px;
    overflow-x: auto;
    margin: 15px 0;
}

.rich-content a {
    color: #409eff;
    text-decoration: none;
}

.rich-content a:hover {
    text-decoration: underline;
}

.default-content p {
    margin-bottom: 15px;
    margin-top: 0;
}
</style>